package com.foreknow.elmboot.service.impl;

import com.foreknow.elmboot.mapper.CartMapper;
import com.foreknow.elmboot.mapper.OrderDetailMapper;
import com.foreknow.elmboot.mapper.OrderMapper;
import com.foreknow.elmboot.po.Cart;
import com.foreknow.elmboot.po.OrderDetail;
import com.foreknow.elmboot.po.Orders;
import com.foreknow.elmboot.service.OrderService;
import com.foreknow.elmboot.util.CommonUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
@Service
public class OrderServiceImpl implements OrderService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private CartMapper cartMapper;
    @Autowired
    private OrderDetailMapper orderDetailMapper;

    @Override
    public List<Orders> orderList(String userId) {
        return orderMapper.orderList(userId);
    }

    @Override
    @Transactional
    public int creatOrder(Orders orders) {
        //从cart表中查询所需要的信息
        Cart cart = new Cart();
        cart.setBusinessId(orders.getBusinessId());
        cart.setUserId(orders.getUserId());
        List<Cart> cartList = cartMapper.listCart(cart);
        //计算总价
        Double orderTotal =cartList.get(0).getBusiness().getDeliveryPrice();
        for(Cart cart1:cartList){
            orderTotal += (cart1.getFood().getFoodPrice()*cart1.getQuantity());
        }
        orders.setOrderTotal(orderTotal);
        //获取下单时间
        orders.setOrderDate(CommonUtil.getCurrentDate());
        //创建订单
        orderMapper.creatOrder(orders);
        //添加订单详情
        Integer orderId = orders.getOrderId();
        List<OrderDetail> list = new ArrayList<>();
        for(Cart cart1:cartList){
            OrderDetail orderDetail = new OrderDetail();
            orderDetail.setOrderId(orderId);
            orderDetail.setFoodId(cart1.getFoodId());
            orderDetail.setQuantity(cart1.getQuantity());
            list.add(orderDetail);
        }
        orderDetailMapper.creatOrderDetail(list);
        //移除购物车
        cartMapper.removeCart(cart);
        return orderId;
    }

    @Override
    public Orders orderById(Integer orderId) {
        return orderMapper.orderById(orderId);
    }

    @Override
    public int payOver(Integer orderId) {
        return orderMapper.payOver(orderId);
    }
}
